<?php


namespace app\admin\controller\business;


use app\common\controller\Adminbase;
use app\admin\model\business\BusinessOrder as BusinessOrderModel;
use app\admin\model\business\Business as BusinessModel;
use think\Db;
use think\facade\Session;

class Businessorder extends Adminbase
{
    protected $searchFields = 'order_no';

    protected function initialize()
    {
        $this->modelClass = new BusinessOrderModel;
        parent::initialize();
    }

    public function index()
    {
        $this->admin1 = Session::get("admin");
        $where2 = array();
        //todo is_del管理员登录状态修改 1 roleid 超级管理员 3分公司 4运营中心
        if ($this->admin1['roleid'] == 3) {
            $admin_where = array(
                'is_del' => 0,
                'status' => 1,
                'roleid' => 4,
                'area_id' => $this->admin1['area_id']
            );
            $admin_ids = Db::name('admin')->where($admin_where)->column('id');

            $business_ids = Db::name('business')
                ->where('belong_admin_id', 'in', $admin_ids)
                ->column('id');;
            $where2[] = ['business_id', 'in', $business_ids];
        }
        if ($this->admin1['roleid'] == 4) {
            $business_ids = Db::name('business')
                ->where('belong_admin_id', $this->admin1['id'])
                ->column('id');;
            $where2[] = ['business_id', 'in', $business_ids];
        }

        $status = input('param.status/d');
        //0待支付 1待发货 2已完成 3待收货 配送中 已发货
        if ($this->request->isAjax()) {
            $where = array();
            $where [] = ['is_del', '=', 0];
            if (isset($status) && $status) {
                $where[] = ['business_order.status', '=', $status];
            }
            // list($page, $limit, $where) = $this->buildTableParames();
            $page = input('page/d', 1);
            $limit = input('limit/d', 10);
            //可能不存在
            $filter = input('filter');
            if ($filter) {
                $filter = json_decode($filter, true);
                if (isset($filter['order_no'])) {
                    $where[] = ['business_order.order_no', 'like', '%' . $filter['order_no'] . '%'];
                }
                if (isset($filter['pay_type'])) {
                    $where[] = ['business_order.pay_type', '=', $filter['pay_type']];
                }
                if (isset($filter['pay_status'])) {
                    $where[] = ['business_order.pay_status', '=', $filter['pay_status']];
                }
                if (isset($filter['status'])) {
                    $where[] = ['business_order.status', '=', $filter['status']];
                }
                if (isset($filter['business_id'])) {
                    $where[] = ['business_order.business_id', '=', $filter['business_id']];
                }
                if (isset($filter['create_time'])) {
                    $create_time = explode(' - ', $filter['create_time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                    $where[] = ['business_order.create_time', 'between', [$create_time[0], $create_time[1]]];
                }
                if (isset($filter['pay_time'])) {
                    $pay_time = explode(' - ', $filter['pay_time']);
                    foreach ($pay_time as $k => $v) {
                        $pay_time[$k] = strtotime($v);
                    }
                    $where[] = ['business_order.pay_time', 'between', [$pay_time[0], $pay_time[1]]];
                }
                if (isset($filter['get_goods_time'])) {
                    $get_goods_time = explode(' - ', $filter['get_goods_time']);
                    foreach ($get_goods_time as $k => $v) {
                        $get_goods_time[$k] = strtotime($v);
                    }
                    $where[] = ['business_order.get_goods_time', 'between', [$get_goods_time[0], $get_goods_time[1]]];
                }
            }
            $search = input('search');
            if ($search) {
                $where[] = ['business_order.order_no', 'like', '%' . $search . '%'];
            }
            $_list = $this->modelClass
                ->where($where2)
                ->where($where)
                ->page($page, $limit)
                ->order('pay_time desc')
                ->order('create_time desc')
                ->withJoin('business')
                ->select();
            foreach ($_list as $k => $v) {
                $_list[$k]['business_name'] = $v['business']['business_name'];
            }
            $total = $this->modelClass
                ->where($where)
                ->where($where2)
                ->withJoin('business')
                ->count();
            $result = ["code" => 0, "count" => $total, "data" => $_list];
            return json($result);
        }
        if (isset($status)) {
            $this->assign('status', $status);
        }
        return $this->fetch('business/business_order/index');
    }

    public function detail()
    {
        $business_order_id = $this->request->param('id/d', 0);
        $goods_list = Db::name('business_order_detail')
            ->where('business_order_id', '=', $business_order_id)
            ->alias('bod')
            ->order('goods.is_kong')
            ->field('bod.*,goods.img')
            ->join('goods', 'bod.goods_id=goods.id')
            ->select();
        $count = Db::name('business_order_detail')
            ->where('business_order_id', '=', $business_order_id)->alias('bod')
            ->field('bod.*,goods.img')
            ->join('goods', 'bod.goods_id=goods.id')->sum('subtotal');
        $business_order = Db::name('business_order')->find($business_order_id);
        $business_info = BusinessModel::find($business_order['business_id']);
        $this->assign("business_info", $business_info);
        $this->assign("business_order", $business_order);
        $this->assign("goods_list", $goods_list);
        $this->assign("count", $count);
        return $this->fetch('business/business_order/detail');
    }

    public function fa()
    {
        $ids = $this->request->param();
        if (Db::name('business_order')->where('id', 'in', $ids['id'])->update(['status' => 3])) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }
    public function pay()
    {
        $data = $this->request->param();
        $id = $data['id'];
        $business_order_info = Db::name('business_order')
            ->find($id);
        if ($business_order_info['pay_status'] == 1) {
            msg(-1, '订单已支付', $business_order_info['pay_status']);
        }
        $update_info = array(
            'id' => $id,
            'status' => 1, //'0待支付 1待发货 2已完成',
            'pay_status' => 1,//'支付状态 0未支付1已支付',
            'pay_type' => 4,//支付方式 1余额支付 2直接支付 3混合支付 4后台支付
            'pay_time' => time()
        );
        $update_id = Db::name('business_order')->update($update_info);
        if ($update_id) {
            return ['code' => 200, 'data' => '', 'msg' => '操作成功'];
        } else {
            return ['code' => 100, 'data' => '', 'msg' => '操作不成功'];
        }
    }

    public function deliver()
    {
        if ($this->request->isPost()) {
            $business_order_id = $this->request->param('business_order_id/d');
            $fa_data = $this->request->param('fa_data');
            $is_all = true;// 拆弹 最后一次完全发货就用本订单编号
            $is_other_all = true;
            foreach ($fa_data as $k => $v) {
                if ($v['to_num'] < 0) {
                    $this->error('发货数量不能小于0！');
                }
                if ($v['to_num'] > $v['dai_num']) {
                    $this->error('发货数量不能大于待发货数量！');
                }
                if ($v['goods_num'] > $v['to_num']) {
                    $is_all = false;
                }
                if (($v['to_num'] != $v['dai_num']) && ($v['goods_num'] != $v['to_num'])) {
                    $is_other_all = false;
                }
            }
            if ($is_all) {
                Db::name('business_order')
                    ->where('id', '=', $business_order_id)
                    ->update(['status' => 3, 'fa_time' => time()]);
                Db::name('business_order_detail')->where('business_order_id', '=', $business_order_id)
                    ->setField(['dai_num' => 0, 'fa_num' => Db::raw('goods_num'),'to_num'=> Db::raw('goods_num')]);
            } else {
                if ($is_other_all) {
                    Db::name('business_order')
                        ->where('id', '=', $business_order_id)
                        ->update(['status' => 3, 'fa_time' => time(), 'is_del' => 1]);
                }
                //todo 进行拆单处理
                //生成同一个订单编号 有父类订单id ，
                $order_info = Db::name('business_order')->find($business_order_id);
                $order_info['porder_id'] = $order_info['id'];
                $order_info['status'] = 3;
                $order_info['create_time'] = time();
                $order_info['fa_time'] = time();
                $order_info['is_del'] = 0;
                unset($order_info['id']);
                $new_id = Db::name('business_order')->insertGetId($order_info);
                $zi = array();
                foreach ($fa_data as $k => $v) {
                    //更改总订单发货详情
                    Db::name('business_order_detail')
                        ->where('id', $k)
                        ->update(
                            [
                                'fa_num' => Db::raw('fa_num+' . $v['to_num']),
                                'dai_num' => Db::raw('dai_num-' . $v['to_num']),
                            ]
                        );
                    //创建子订单发货详情
                    $zi_order_detail = Db::name('business_order_detail')
                        ->where('id', $k)
                        ->find();
                    unset($zi_order_detail['id']);
                    $zi_order_detail['business_order_id'] = $new_id;
                    $zi_order_detail['to_num'] = $v['to_num'];
                    if ($v['to_num']==0){
                        $zi_order_detail['business_confirm']=1;
                    }
//                    $zi_order_detail['fa_num'] = $v['to_num'];
//                    $zi_order_detail['dai_num'] = 0;
                    $zi[] = $zi_order_detail;
                }
                Db::name('business_order_detail')->insertAll($zi);
            }
            $this->success('操作成功！');
        } else {
            $business_order_id = $this->request->param('id/d', 0);
            $goods_list = Db::name('business_order_detail')
                ->where('business_order_id', '=', $business_order_id)
                ->alias('bod')
                ->order('goods.is_kong')
                ->field('bod.*,goods.img,goods.id as goods_id,goods.is_water,goods.is_kong')
                ->join('goods', 'bod.goods_id=goods.id')
                ->select();
            $this->assign("goods_list", $goods_list);
            $this->assign("business_order_id", $business_order_id);
            return $this->fetch('business/business_order/deliver');
        }
    }

    public function faDetail()
    {
        $business_order_id = $this->request->param('id/d', 0);
        $goods_list = Db::name('business_order_detail')
            ->where('business_order_id', '=', $business_order_id)
            ->alias('bod')
            ->order('goods.is_kong')
            ->field('bod.*,goods.img,goods.id as goods_id,goods.is_kong')
            ->join('goods', 'bod.goods_id=goods.id')
            ->select();
        foreach ($goods_list as $k=>$v){
            if($v['business_confirm']==1){
                $goods_list[$k]['business_confirm']='已收货';
            }else{
                $goods_list[$k]['business_confirm']='未确认';
            }
            if($v['confirm_time']){
                $goods_list[$k]['confirm_time']=date('Y-m-d H:i',$v['confirm_time']);
            }else{
                $goods_list[$k]['confirm_time']='——————';
            }
        }
        $this->assign("goods_list", $goods_list);
        $this->assign("business_order_id", $business_order_id);
        return $this->fetch('business/business_order/dadetail');
    }
}